package com.pig4cloud.pig.mt.manage;

import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.mt.entity.WxUser;
import com.pig4cloud.pig.mt.service.WxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 用户表
 *
 * @author niefy
 * @email niefy@qq.com
 * @date 2020-03-07 13:55:23
 */
@RestController
@RequestMapping("/manage/wxUser")
@Api(value = "/manage/wxUser", tags = "公众号用户管理")
public class WxUserManageController {
    @Autowired
    private WxUserService userService;
    @Autowired
    private WxMpService wxMpService;

    /**
     * 列表
     */
    @ApiOperation(value = "列表", notes = "列表")
    @GetMapping("/list")
	@PreAuthorize("@pms.hasPermission('mt_wxuser_add')" )
    public R list(@CookieValue String appid, @RequestParam Map<String, Object> params) {
        params.put("appid", appid);
        return R.ok(userService.queryPage(params));
    }

    /**
     * 列表
     */
    @ApiOperation(value = "列表", notes = "列表")
    @PostMapping("/listByIds")
	@PreAuthorize("@pms.hasPermission('mt_wxuser_add')" )
    public R listByIds(@CookieValue String appid, @RequestBody String[] openids) {
        List<WxUser> users = userService.listByIds(Arrays.asList(openids));
        return R.ok(users);
    }


    /**
     * 信息
     */
    @ApiOperation(value = "信息", notes = "信息")
    @GetMapping("/info/{openid}")
	@PreAuthorize("@pms.hasPermission('mt_wxuser_get')" )
    public R info(@CookieValue String appid, @PathVariable("openid") String openid) {
        WxUser wxUser = userService.getById(openid);

        return R.ok(wxUser);
    }

    /**
     * 同步用户列表
     */
    @ApiOperation(value = "同步用户列表", notes = "同步用户列表")
	@SysLog("同步用户列表")
    @PostMapping("/syncWxUsers")
	@PreAuthorize("@pms.hasPermission('mt_wxuser_add')" )
    public R syncWxUsers(@CookieValue String appid) {
        wxMpService.switchoverTo(appid);
        userService.syncWxUsers(appid);

        return R.ok("任务已建立");
    }


    /**
     * 删除
     */
    @ApiOperation(value = "删除用户", notes = "删除用户")
    @SysLog("删除用户")
    @DeleteMapping("/delete")
	@PreAuthorize("@pms.hasPermission('mt_wxuser_del')" )
    public R delete(@CookieValue String appid, @RequestBody String[] ids) {
        userService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
